<!-- 创建时间: 2020年12月27日 星期天 13:09 -->
<template>
    <div class="startExamination_container"
         id="startExamination_container">
        <el-card class="box-card"
                 v-for="(item, i) in questionsList"
                 :key="i">
            <div slot="header"
                 class="clearfix">
                <div v-if="item.type == 'radio'">
                    <b>【{{ "选择题-" + (i + 1) }}】</b>
                </div>
                <div v-if="item.type == 'checkbox'">
                    <b>【{{ "多选题-" + (i + 1) }}】</b>
                </div>
                {{ item.questionName }} （ {{ item.score }}分 ）
            </div>
            <div class="text item">
                <div v-if="item.type == 'radio'"
                     class="optionListStyle">
                    <div v-for="(ite, j) in item.optionList"
                         :key="j">
                        <el-radio v-model="item.rightOption"
                                  :label="ite">{{ ite }}
                        </el-radio>
                    </div>
                </div>
                <div v-if="item.type == 'checkbox'"
                     class="optionListStyle">
                    <el-checkbox-group v-model="item.rightOption">
                        <div v-for="(ite, j) in item.optionList"
                             :key="j">
                            <el-checkbox :label="ite">{{ ite }}</el-checkbox>
                        </div>
                    </el-checkbox-group>
                </div>
            </div>
        </el-card>

        <el-row>
            <el-col style="text-align:right; padding:0px 10px;">
                <el-button type="primary"
                           style="padding: 12px 35px;"
                           round
                           @click="submit">交卷</el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data () {
        //这里存放数据
        return {
            questionsList: [], // 下载到时前端的考试试题信息
            endTime: this.$store.getters.getEndTime,
            isNext: false,
        };
    },
    // 离开该路由前的路由守卫
    beforeRouteLeave: function (to, from, next) {
        next(this.isNext);
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        autoGetExaminationQuestions () {
            let classNumber = this.$store.getters.getUserNumber.substring(0, 7);
            this.$http
                .post("autoGetExaminationQuestions", {
                    classNumber: classNumber,
                    questionBank: this.$store.getters.getStartExaminationNumber,
                })
                .then((res) => {
                    let data = JSON.parse(res.bodyText);
                    for (let i = 0; i < data.length; i++) {
                        data[i].optionList = data[i].optionList.split("&");
                        data[i].rightOption = [];
                    }
                    this.questionsList = data;
                });

            let dt = setInterval(() => {
                let date = new Date();
                let formatEndTime = new Date(this.endTime);
                let effectiveTime = Math.round(
                    formatEndTime.getTime() - date.getTime()
                );
                if (effectiveTime <= 0) {
                    effectiveTime = 0;
                    clearInterval(dt);
                }
                // 把毫秒转为秒
                effectiveTime = Math.floor(effectiveTime / 1000);
                // 时
                let hours = Math.floor(effectiveTime / 60 / 60) % 24;
                // 分
                let minute = Math.floor((effectiveTime / 60) % 60);
                // 秒
                let second = Math.floor(effectiveTime % 60);
                let message = "";
                if (hours > 0) message = hours + ":" + minute + ":" + second;
                else message = minute + ":" + second;
                this.$emit("getMessage", message);
            }, 1000);

            this.$once("hook:beforeDestroy", () => {
                clearInterval(dt);
            });
        },
        submit () {
            let questionsList = this.questionsList;
            let rightOption = [];
            for (let i = 0; i < questionsList.length; i++) {
                let arr = new Array();
                arr.push(questionsList[i].id);
                if (questionsList[i].type == "radio") {
                    arr.push(questionsList[i].rightOption);
                } else {
                    arr.push(
                        questionsList[i].rightOption
                            .join(",")
                            .replace(/,/g, "&")
                    );
                }
                rightOption.push(arr);
            }

            let obj = {
                classNumber: this.$store.getters.getUserNumber.substring(0, 7),
                studentNumber: this.$store.getters.getUserNumber,
                questionBank: this.$store.getters.getStartExaminationNumber,
                rightOption: rightOption,
            };

            this.$http
                .post("submitExaminationInfo", {
                    data: JSON.stringify(obj)
                })
                .then((res) => {
                    this.isNext = true;
                    if (res.body) {
                        this.$message.success(
                            "恭喜你，完成本次" +
                            this.$route.query.coursesName +
                            "课程考试"
                        );
                        this.$router.push("/student/myExamination");
                    } else {
                        this.$message.error(
                            "你已超时，本次" +
                            this.$route.query.coursesName +
                            "课程考试已结束"
                        );
                        this.$router.push("/student/myExamination");
                    }
                });
        },
        startExamination_container_mouseEvent () {
            let mouseEv_count = sessionStorage.getItem("mouseEv_count");
            if (mouseEv_count == null) {
                sessionStorage.setItem("mouseEv_count", 1);
            } else if (mouseEv_count >= 2) {
                this.$message({
                    type: "error",
                    message: "考生你好，由于你存在违规行为，本场考试将记0分处理！",
                    duration: 6000,
                });
                this.isNext = true;
                this.submit();
                return;
            } else {
                sessionStorage.setItem("mouseEv_count", ++mouseEv_count);
            }
            this.$message({
                type: "warning",
                message: "考生你好，现你存在" +
                    sessionStorage.getItem("mouseEv_count") +
                    "次违规行为，请诚信参考！",
                duration: 6000,
            });
        },
        visibilitychange () {
            let pageVisibility = document.visibilityState;
            // 页面变为不可见时触发
            if (pageVisibility == "hidden") { }
            // 页面变为可见时触发
            if (pageVisibility == "visible") {
                this.startExamination_container_mouseEvent();
            }
        },
        documentEvent () {
            // 添加事件监听
            document.addEventListener(
                "visibilitychange",
                this.visibilitychange
            );
        },
    },
    beforeDestroy () {
        sessionStorage.removeItem("mouseEv_count");
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created () {
        this.autoGetExaminationQuestions();
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
        if (sessionStorage.getItem("mouseEv_count") == null) {
            document.removeEventListener(
                "visibilitychange",
                this.visibilitychange
            );
            this.documentEvent();
        }
    },
    //当data中定义的数据有变化时就会加载updated方法
    updated () { },
};
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
.startExamination_container {
    // border: 3px solid red;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;

    .box-card {
        margin: 15px;

        .optionListStyle {
            div {
                border-bottom: 1px solid gainsboro;

                label {
                    padding: 10px 10px;
                }
            }
        }
    }
}
</style>
